<template>
  <div class="modules-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2 class="page-title">
          <el-icon><Grid /></el-icon>
          模块列表
        </h2>
        <p class="page-description">
          {{ appStore.currentProductName }} - 共 {{ modulesStore.total }} 个模块
        </p>
      </div>
      <div class="header-actions">
        <el-button
          type="primary"
          :icon="Refresh"
          @click="refreshData"
          :loading="modulesStore.loading"
        >
          刷新数据
        </el-button>
        <el-button
          :icon="Download"
          @click="exportData"
          :disabled="modulesStore.loading"
        >
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :inline="true" @submit.prevent="applyFilters" class="search-form">
        <el-form-item label="搜索模块">
          <el-input
            v-model="localFilters.search"
            placeholder="名称、子系统、组件..."
            :prefix-icon="Search"
            clearable
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item label="模块分组">
          <el-select
            v-model="localFilters.modGroup"
            placeholder="全部分组"
            clearable
            style="width: 180px"
          >
            <el-option label="内核" value="kernel" />
            <el-option label="驱动" value="driver" />
            <el-option label="系统服务" value="system" />
            <el-option label="应用" value="app" />
            <el-option label="三方库" value="third-party" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Filter" @click="applyFilters">筛选</el-button>
          <el-button :icon="RefreshLeft" @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 模块表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="modulesStore.loading"
        :data="modulesStore.paginatedModules"
        style="width: 100%"
        row-key="id"
        @sort-change="onSortChange"
        stripe
      >
        <el-table-column prop="id" label="ID" width="80" sortable="custom" />
        <el-table-column prop="name" label="模块名称" min-width="250" sortable="custom">
          <template #default="{ row }">
            <el-link
              type="primary"
              :underline="false"
              @click="viewModuleDetail(row.id)"
            >
              {{ row.name }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="subsystem" label="子系统" width="150" sortable="custom" />
        <el-table-column prop="componentName" label="组件" width="150" sortable="custom" />
        <el-table-column prop="modGroup" label="分组" width="120" sortable="custom" />
        <el-table-column prop="deps_total" label="总依赖" width="100" align="center" sortable="custom">
          <template #default="{ row }">
            <el-tag type="success" size="small">{{ row.deps_total || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dependedBy" label="被依赖" width="100" align="center" sortable="custom">
          <template #default="{ row }">
            <el-tag type="info" size="small">{{ row.dependedBy || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              link
              @click="viewModuleDetail(row.id)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          :current-page="modulesStore.currentPage"
          :page-size="modulesStore.pageSize"
          :total="modulesStore.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Grid,
  Refresh,
  Download,
  Search,
  Filter,
  RefreshLeft
} from '@element-plus/icons-vue'
import { useModulesStore } from '@/stores/modules'
import { useAppStore } from '@/stores/app'

const modulesStore = useModulesStore()
const appStore = useAppStore()
const router = useRouter()

// 本地筛选条件，避免直接修改store
const localFilters = reactive({
  search: '',
  modGroup: ''
})

// 方法
const refreshData = async () => {
  if (!appStore.currentProduct) {
    ElMessage.warning('请先选择一个产品版本')
    return
  }
  try {
    await modulesStore.fetchModules()
    ElMessage.success('模块数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  }
}

const exportData = () => {
  ElMessageBox.confirm('确定要导出当前筛选结果的模块数据吗？', '确认导出', {
    type: 'info',
    confirmButtonText: '导出CSV',
    cancelButtonText: '取消',
  }).then(async () => {
    try {
      const blob = await modulesStore.exportModules('csv');
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      const timestamp = new Date().toISOString().slice(0, 19).replace(/[:-]/g, '');
      link.href = url;
      link.download = `modules_${appStore.currentProductName}_${timestamp}.csv`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      ElMessage.success('模块数据导出成功');
    } catch (error) {
      ElMessage.error('导出失败，请重试');
    }
  }).catch(() => {});
}

const applyFilters = () => {
  modulesStore.setFilters(localFilters)
}

const resetFilters = () => {
  localFilters.search = ''
  localFilters.modGroup = ''
  modulesStore.clearFilters()
}

const onSortChange = ({ prop, order }) => {
  const sortOrder = order === 'ascending' ? 'asc' : 'desc';
  modulesStore.setFilters({ sortBy: prop, sortOrder });
}

const handleSizeChange = (size) => {
  modulesStore.setPageSize(size)
}

const handleCurrentChange = (page) => {
  modulesStore.setCurrentPage(page)
}

const viewModuleDetail = (moduleId) => {
  router.push({
    name: 'ModuleDetail',
    params: { id: moduleId }
  })
}

// 监听产品变化
watch(() => [appStore.currentProduct, appStore.currentVersion], () => {
  if (appStore.currentProduct) {
    modulesStore.fetchModules()
  }
}, { immediate: true })

// 生命周期
onMounted(() => {
  if (!appStore.currentProduct && appStore.products.length > 0) {
      appStore.setCurrentProduct(appStore.products[0].id)
  }
  if (appStore.currentProduct) {
      modulesStore.fetchModules()
  }
})
</script>

<style scoped lang="scss">
.modules-page {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .header-content {
      .page-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin: 0 0 8px 0;
        font-size: 24px;
        font-weight: 600;
      }
      .page-description {
        margin: 0;
        color: var(--el-text-color-secondary);
      }
    }
  }

  .search-card {
    margin-bottom: 20px;
    .search-form .el-form-item {
      margin-bottom: 0;
    }
  }

  .table-card {
    .el-table .el-link {
      font-weight: 500;
    }
    .pagination-wrapper {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
